package com.genshang.restaurant.util.youzan;


import com.alibaba.fastjson.JSON;
import com.youzan.cloud.open.sdk.core.client.auth.Token;
import com.youzan.cloud.open.sdk.core.client.core.DefaultYZClient;
import com.youzan.cloud.open.sdk.core.client.core.YouZanClient;
import com.youzan.cloud.open.sdk.core.oauth.model.OAuthToken;
import com.youzan.cloud.open.sdk.core.oauth.token.TokenParameter;
import com.youzan.cloud.open.sdk.gen.v1_0_0.api.YouzanCrmCustomerPointsGet;
import com.youzan.cloud.open.sdk.gen.v1_0_0.api.YouzanUserOpenidGetbyopenid;
import com.youzan.cloud.open.sdk.gen.v1_0_0.api.YouzanUsersAccountCheck;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.*;
import com.youzan.cloud.open.sdk.gen.v3_0_1.api.YouzanUserBasicGet;
import com.youzan.cloud.open.sdk.gen.v3_0_1.model.YouzanUserBasicGetParams;
import com.youzan.cloud.open.sdk.gen.v3_0_1.model.YouzanUserBasicGetResult;
import com.youzan.cloud.open.sdk.gen.v4_0_0.api.YouzanCrmCustomerPointsDecrease;
import com.youzan.cloud.open.sdk.gen.v4_0_0.api.YouzanCrmCustomerPointsIncrease;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsDecreaseParams;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsDecreaseResult;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsIncreaseParams;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsIncreaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 有赞工具类，参考下列网址
 * <p>
 * https://doc.youzanyun.com/doc#/content/27034/29006
 * https://doc.youzanyun.com/doc#/content/27027/27062
 * https://doc.youzanyun.com/doc#/content/35701/36458
 */
public class YouZanUtil {

    // 三方应用id
    static String clientId = "3f8c116ffead25f4d2";
    static String clientSecret = "179f03ac70ca1ecf2680d959532a335a";

    // 店铺ID
//    static Long ktdId = 91102894L;

    // 店铺ID
    static Long ktdId = 46147916L;


    // 业务唯一标示
    static String biz_value = "";

    static OAuthToken oAuthToken;

    // 电话国际码
    static String country_code = "+86";

    // 默认客户端
    static DefaultYZClient defaultYZClient;

    static Logger LOGGER = LoggerFactory.getLogger(YouZanUtil.class);

    /**
     * 获取授权Token
     *
     * @https://doc.youzanyun.com/doc#/content/35701/36467 Tips：refresh值传false表示不需要获取刷新令牌refresh_token；
     * refresh值传true表示需要获取刷新令牌refresh_token，
     * 之后可以根据这个refresh_token获取新的access_token。
     */
    public static OAuthToken getOAuthToken() {
        try {
            if (null != oAuthToken) {
                return oAuthToken;
            }
            DefaultYZClient yzClient = new DefaultYZClient();
            TokenParameter tokenParameter = TokenParameter.self()
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .grantId(ktdId.toString())
                    .refresh(false)
                    .build();
            oAuthToken = yzClient.getOAuthToken(tokenParameter);
            return oAuthToken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static DefaultYZClient getYzClient() {
        if (null != defaultYZClient) {
            return defaultYZClient;
        }
        if (null != oAuthToken) {
            getOAuthToken();
        }
        return new DefaultYZClient();
    }

    /**
     * 查询是否存在有赞帐号
     * https://doc.youzanyun.com/doc#/content/API/1-308/detail/api/0/21
     *
     * @param phone
     * @return
     */
    public static YouzanUsersAccountCheckResult checkUser(String phone) {
        LOGGER.info("查询是否存在有赞帐号");
        try {
            //YouZanClient 建议全局唯一,使用 spring 容器管理
            YouZanClient yzClient = getYzClient();
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanUsersAccountCheck youzanUsersAccountCheck = new YouzanUsersAccountCheck();
            //创建参数对象,并设置参数
            YouzanUsersAccountCheckParams youzanUsersAccountCheckParams = new YouzanUsersAccountCheckParams();
            youzanUsersAccountCheckParams.setAccountType("Mobile");
            youzanUsersAccountCheckParams.setAccountId(phone);
            youzanUsersAccountCheck.setAPIParams(youzanUsersAccountCheckParams);

            YouzanUsersAccountCheckResult result = yzClient.invoke(youzanUsersAccountCheck, token, YouzanUsersAccountCheckResult.class);
            LOGGER.info(JSON.toJSONString(result));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过手机号获取有赞用户信息
     * https://doc.youzanyun.com/doc#/content/API/1-308/detail/api/0/522
     *
     * @param phone
     * @return
     */
    public static YouzanUserBasicGetResult getUserInfoByPhone(String phone, String yzOpenId) {
        try {
            LOGGER.info("通过手机号获取有赞用户信息");

            //创建 YZClient
            DefaultYZClient yzClient = getYzClient();
            //创建 Auth 验证方式对象
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanUserBasicGetParams youzanUserBasicGetParams = new YouzanUserBasicGetParams();
            youzanUserBasicGetParams.setCountryCode(country_code);
            youzanUserBasicGetParams.setMobile(phone);
            YouzanUserBasicGet youzanUserBasicGet = new YouzanUserBasicGet();
            youzanUserBasicGet.setAPIParams(youzanUserBasicGetParams);
            YouzanUserBasicGetResult youzanUserBasicGetResult = yzClient.invoke(youzanUserBasicGet, token, YouzanUserBasicGetResult.class);
            LOGGER.info(JSON.toJSONString(youzanUserBasicGetResult));
            return youzanUserBasicGetResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过有赞OpenId获取用户积分
     *
     * @param yzOpenId
     * @return
     */
    public static YouzanCrmCustomerPointsGetResult getPointByYzOpenId(String yzOpenId) {
        try {
            LOGGER.info("通过有赞OpenId获取用户积分");

            //1.创建 YZClient
            DefaultYZClient yzClient = getYzClient();
            YouzanCrmCustomerPointsGetParams youzanCrmCustomerPointsGetParams = new YouzanCrmCustomerPointsGetParams();
            YouzanCrmCustomerPointsGetParams.YouzanCrmCustomerPointsGetParamsUser user = new YouzanCrmCustomerPointsGetParams.YouzanCrmCustomerPointsGetParamsUser();
            user.setAccountId(yzOpenId);
            user.setAccountType(5);
            youzanCrmCustomerPointsGetParams.setUser(user);
            YouzanCrmCustomerPointsGet youzanCrmCustomerPointsGet = new YouzanCrmCustomerPointsGet();
            youzanCrmCustomerPointsGet.setAPIParams(youzanCrmCustomerPointsGetParams);
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanCrmCustomerPointsGetResult youzanCrmCustomerPointsGetResult = yzClient.invoke(youzanCrmCustomerPointsGet, token, YouzanCrmCustomerPointsGetResult.class);
            LOGGER.info(JSON.toJSONString(youzanCrmCustomerPointsGetResult));
            return youzanCrmCustomerPointsGetResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 减有赞积分
     * https://doc.youzanyun.com/doc#/content/API/1-371/detail/api/0/873
     *
     * @param yzOpenId
     * @return
     */
    public static YouzanCrmCustomerPointsDecreaseResult decreasePoint(String yzOpenId, String reason, Integer points) {
        try {
            LOGGER.info("减有赞积分");

            //1.创建 YZClient
            DefaultYZClient yzClient = getYzClient();
            YouzanCrmCustomerPointsDecreaseParams youzanCrmCustomerPointsDecreaseParams = new YouzanCrmCustomerPointsDecreaseParams();
            YouzanCrmCustomerPointsDecreaseParams.YouzanCrmCustomerPointsDecreaseParamsUser user = new YouzanCrmCustomerPointsDecreaseParams.YouzanCrmCustomerPointsDecreaseParamsUser();
            user.setAccountId(yzOpenId);
            user.setAccountType(5);
            YouzanCrmCustomerPointsDecreaseParams.YouzanCrmCustomerPointsDecreaseParamsParams youzanCrmCustomerPointsDecreaseParamsParams = new YouzanCrmCustomerPointsDecreaseParams.YouzanCrmCustomerPointsDecreaseParamsParams();
            youzanCrmCustomerPointsDecreaseParamsParams.setUser(user);
            youzanCrmCustomerPointsDecreaseParamsParams.setPoints(points);
            youzanCrmCustomerPointsDecreaseParamsParams.setReason(reason);
            youzanCrmCustomerPointsDecreaseParamsParams.setKdtId(ktdId);
            youzanCrmCustomerPointsDecreaseParamsParams.setBizValue(biz_value);
            youzanCrmCustomerPointsDecreaseParamsParams.setClientId(clientId);
            youzanCrmCustomerPointsDecreaseParams.setParams(youzanCrmCustomerPointsDecreaseParamsParams);
            YouzanCrmCustomerPointsDecrease youzanCrmCustomerPointsDecrease = new YouzanCrmCustomerPointsDecrease();
            youzanCrmCustomerPointsDecrease.setAPIParams(youzanCrmCustomerPointsDecreaseParams);
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanCrmCustomerPointsDecreaseResult youzanCrmCustomerPointsDecreaseResult = yzClient.invoke(youzanCrmCustomerPointsDecrease, token, YouzanCrmCustomerPointsDecreaseResult.class);
            LOGGER.info(JSON.toJSONString(youzanCrmCustomerPointsDecreaseResult));
            return youzanCrmCustomerPointsDecreaseResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 增加有赞积分
     * https://doc.youzanyun.com/doc#/content/API/1-371/detail/api/0/872
     *
     * @return
     */
    public static YouzanCrmCustomerPointsIncreaseResult increasePoint(String yzOpenId, String reason, Integer points) {
        try {
            LOGGER.info("增加有赞积分");
            //1.创建 YZClient
            DefaultYZClient yzClient = getYzClient();
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanCrmCustomerPointsIncrease youzanCrmCustomerPointsIncrease = new YouzanCrmCustomerPointsIncrease();
            YouzanCrmCustomerPointsIncreaseParams.YouzanCrmCustomerPointsIncreaseParamsParams params = new YouzanCrmCustomerPointsIncreaseParams.YouzanCrmCustomerPointsIncreaseParamsParams();
            params.setReason(reason);
            params.setKdtId(ktdId);
            params.setBizValue(System.currentTimeMillis() + "");
            params.setPoints(points);
            YouzanCrmCustomerPointsIncreaseParams.YouzanCrmCustomerPointsIncreaseParamsUser user = new YouzanCrmCustomerPointsIncreaseParams.YouzanCrmCustomerPointsIncreaseParamsUser();
            user.setAccountType(5);
            user.setAccountId(yzOpenId);
            params.setUser(user);
            //创建参数对象,并设置参数
            YouzanCrmCustomerPointsIncreaseParams youzanCrmCustomerPointsIncreaseParams = new YouzanCrmCustomerPointsIncreaseParams();
            youzanCrmCustomerPointsIncreaseParams.setParams(params);
            youzanCrmCustomerPointsIncrease.setAPIParams(youzanCrmCustomerPointsIncreaseParams);
            YouzanCrmCustomerPointsIncreaseResult result = yzClient.invoke(youzanCrmCustomerPointsIncrease, token, YouzanCrmCustomerPointsIncreaseResult.class);
            LOGGER.info(JSON.toJSONString(result));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * https://doc.youzanyun.com/doc#/content/API/1-308/detail/api/0/831
     * 根据微信openid查询有赞openid
     *
     * @param wxOpenid
     * @return
     */
    public static YouzanUserOpenidGetbyopenidResult getYouzanOpenid(String wxOpenid) {
        try {
            LOGGER.info("根据微信openid查询有赞openid");
            //YouZanClient 建议全局唯一,使用 spring 容器管理
            YouZanClient yzClient = new DefaultYZClient();
            Token token = new Token(getOAuthToken().getAccessToken());
            YouzanUserOpenidGetbyopenid youzanUserOpenidGetbyopenid = new YouzanUserOpenidGetbyopenid();
            //创建参数对象,并设置参数
            YouzanUserOpenidGetbyopenidParams youzanUserOpenidGetbyopenidParams = new YouzanUserOpenidGetbyopenidParams();
            youzanUserOpenidGetbyopenidParams.setOpenId(wxOpenid);
            youzanUserOpenidGetbyopenidParams.setWechatType(1);
            youzanUserOpenidGetbyopenid.setAPIParams(youzanUserOpenidGetbyopenidParams);
            YouzanUserOpenidGetbyopenidResult result = yzClient.invoke(youzanUserOpenidGetbyopenid, token, YouzanUserOpenidGetbyopenidResult.class);
            LOGGER.info(JSON.toJSONString(result));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
